import { apigetList } from '../api'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { StoreStateType } from '../interface'
import { Select } from 'antd';
import { useNavigate } from 'react-router-dom'

const { Option } = Select;

const Home = () => {

    const dispatch = useDispatch()
    
    const navigate = useNavigate()

    // 获取redux中的list数据
    const list = useSelector((state: StoreStateType) => state.list)

    // 保存当前页码
    const [current, setCurrent] = useState(1)

    // 宫格样式
    const [num, setNum] = useState("20%")

    useEffect(() => {
        getList()
    }, [current])

    // 获取列表数据
    const getList = () => {
        apigetList({ current }).then(res => {
            // 将获取到的 list数据 保存到redux中
            dispatch({ type: 'CHANGE_LIST', data: res.data })
        })
    }

    // 改变宫格样式
    const changeNum = (data: string) => {
        setNum(data)
    }

    // 上拉加载
    const changeScroll = (e: any) => {
        // 轮动条距离页面顶部的高度
        const STop = e.target.scrollTop // 滚动条距离页面顶部的高度

        const SHeight = e.target.scrollHeight // 滚动条的高度

        const OHeight = e.target.offsetHeight // 页面的高度

        if(SHeight - STop - OHeight <= 0) {
            //  如果到底了 就要加载数据
            setCurrent(current + 1)

        } 
    }

    // 跳转详情页
    const toDetail = (data:any) => {
        
        navigate(`/detail/${data.id}`)
    }


    return <div className="home-box">
        <div className="home-header">
            <Select value={num} style={{ width: "100%" }} onChange={changeNum}>
                <Option value="20%">一屏25等分</Option>
                <Option value="33.3%">一屏9等分</Option>
            </Select>
        </div>
        <div className="list-box" onScroll={changeScroll}>
            {/* 渲染list */}
            {
                list.length && list.map((item, idx) => {
                    return <div onClick={() => toDetail(item)} key={idx} className="list-item" style={{ width: num, height: num }}>
                        <img src={item.img} alt="" />
                        <p>{item.name}</p>
                    </div>
                })
            }
        </div>


    </div>
}

export default Home